package libs

import (
	"golang.org/x/time/rate"
	"log"
	"runtime"
	"strconv"
)

var (
	Loger *log.Logger
	Conf  *Config
	Path  string
)

type Config struct {
	PidFile    string     `goconf:"pidfile"`
	Log        string     `goconf:"log"`
	DirUpload  string     `goconf:"dir.upload"`
	DirThumb   string     `goconf:"dir.thumb"`
	MaxProc    int        `goconf:"maxproc"`
	LimitRate  rate.Limit `goconf:"limit.rate"`
	LimitBurst int        `goconf:"limit.burst"`
	TCPAddr    string     `goconf:"tcp.addr"`
	TLSAddr    string     `goconf:"tls.addr"`
	TLSCert    string     `goconf:"tls.cert"`
	TLSKey     string     `goconf:"tls.key"`
	SALT       string     `goconf:"salt"`
	RedisAddr  string     `goconf:"redis.addr"`
	RedisDB    int        `goconf:"redis.db"`
}

func ConfigRead() *Config {
	configMap := ConfigInit("./upload.conf")
	config := &Config{
		PidFile:    "./upload.pid",
		Log:        "./upload.log",
		DirUpload:  "./uploads/upload/",
		DirThumb:   "./uploads/thumb/",
		MaxProc:    runtime.NumCPU(),
		LimitRate:  10,
		LimitBurst: 10,
		TCPAddr:    ":8080",
		TLSAddr:    ":8888",
		TLSCert:    "",
		TLSKey:     "",
		SALT:       "JonGates",
		RedisAddr:  "",
		RedisDB:    15,
	}
	if configMap["pidfile"] != "" {
		config.PidFile = configMap["pidfile"]
	}
	if configMap["log"] != "" {
		config.Log = configMap["log"]
	}
	if configMap["dir.upload"] != "" {
		config.DirUpload = configMap["dir.upload"]
	}
	if configMap["dir.thumb"] != "" {
		config.DirThumb = configMap["dir.thumb"]
	}
	if configMap["maxproc"] != "" {
		i, err := strconv.Atoi(configMap["maxproc"])
		if err != nil {
			panic(err)
		}
		config.MaxProc = i
	}
	if configMap["limit.rate"] != "" {
		i, err := strconv.Atoi(configMap["limit.rate"])
		if err != nil {
			panic(err)
		}
		config.LimitRate = rate.Limit(i)
	}
	if configMap["limit.burst"] != "" {
		i, err := strconv.Atoi(configMap["limit.burst"])
		if err != nil {
			panic(err)
		}
		config.LimitBurst = i
	}
	if configMap["tcp.addr"] != "" {
		config.TCPAddr = configMap["tcp.addr"]
	}
	if configMap["tls.addr"] != "" {
		config.TLSAddr = configMap["tls.addr"]
	}
	if configMap["tls.cert"] != "" {
		config.TLSCert = configMap["tls.cert"]
	}
	if configMap["tls.key"] != "" {
		config.TLSKey = configMap["tls.key"]
	}
	if configMap["salt"] != "" {
		config.SALT = configMap["salt"]
	}
	if configMap["redis.addr"] != "" {
		config.RedisAddr = configMap["redis.addr"]
	}
	if configMap["redis.db"] != "" {
		i, err := strconv.Atoi(configMap["redis.db"])
		if err != nil {
			panic(err)
		}
		config.RedisDB = i
	}
	Conf = config
	return config
}
